#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
   @Author: 即将拥有人鱼线的yjw
   @Time: 2024/3/7 15:46
   @File: risk_review_index_task.py
   @desc: 调度执行调度任务
"""
import json

from AmlScripts.BasicFunction.common_test_prepare import common_test_prepare
from CommonScripts.index_rule_cal import indexJobAction
from AmlScripts.Schedule.scheduled_tasks import run_refresh_task_cache
from BladeFerm.Lib.Common import logger
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.lib.utils.variable import Variable
from BladeFerm.databases import DB_APP

bladeVer = Variable()


def modify_rule_params(input_data=None, ui_expect=None):
    '''
    修改页面参数
    '''
    rule_no = input_data.get('规则编号', None)
    rule_version = input_data.get('规则版本', None)
    parameter_name = input_data.get('参数名', None)
    parameter_value = input_data.get('参数值', '')
    logger.info(f'规则{rule_no}-{rule_version}修改参数为: {parameter_name}={parameter_value}')
    if rule_no and rule_version and parameter_name and parameter_value:
        # STEP1:修改规则参数
        modify_sql = (f"update hsamlls.amlls_cfg_ruleparameter set parameter_value='1' "
                      f"where rules_no = 'D001' and rule_version_list like '%{rule_version}%' "
                      f"and parameter_name = '{parameter_name}' ")
        DB_APP.run_one_sql(modify_sql)
        # STEP2:刷新缓存
        run_refresh_task_cache(input_data, ui_expect)
    else:
        logger.warning('未传入期望参数[规则编号, 规则版本, 参数名， 参数值]，请检查！')
        raise SeleniumError('未传入期望参数[规则编号, 规则版本, 参数名， 参数值]，请检查！')


@common_test_prepare
def run_rule_task(input_data=None, ui_expect=None):
    '''
    子项调度任务执行、断言、修改页面参数
    '''
    # STEP1:装饰器内执行数据预埋
    env = bladeVer.get_variable('varg_db_type')
    task_no = input_data.get('任务编号', 'SuspiciousRulRunTask')
    rule_no = input_data.get('规则编号', 'none')
    test_date = input_data.get('日期', '20240321')
    logger.info(f'任务标号为: {task_no}')
    if rule_no:  # 通过入参为任务编号来执行调度任务和用户得分断言
        blade_rule_no = bladeVer.get_variable("varg_blade_rule_no")
        run_task_flag = True
        if blade_rule_no and blade_rule_no == rule_no:
            # STEP2: 判断是否修改参数并刷新过缓存？刷新缓存了，则需要重新执行规则任务
            refresh_cache_server = bladeVer.get_variable("varg_refresh_cache_flag")
            if refresh_cache_server and 'TRUE' == refresh_cache_server:
                run_task_flag = True
                bladeVer.set_variable("varg_refresh_cache_flag", "FALSE")
            else:
                run_task_flag = False
                logger.info(f'任务编号{task_no}已经执行，跳过直接断言！')
        if run_task_flag:
            bladeVer.set_variable("varg_blade_rule_no", rule_no)  # 更新任务编号
            task_params = {
                "proposal_no": {"name": "proposal_no", "value": "0", "custom": True, "direct": "", "index": 0},
                "rules_no": {"name": "rules_no", "value": rule_no, "custom": True, "direct": "", "index": 1},
                "p_begin_date": {"name": "p_begin_date", "value": test_date, "custom": True, "direct": "", "index": 2},
                "p_end_date": {"name": "p_end_date", "value": test_date, "custom": True, "direct": "", "index": 3},
                "p_init_date": {"name": "p_init_date", "value": test_date, "custom": True, "direct": "", "index": 4},
                "bBeginDate": {"name": "bBeginDate", "value": test_date, "custom": True, "direct": "", "index": 5},
                "bEndDate": {"name": "bEndDate", "value": test_date, "custom": True, "direct": "", "index": 6},
                "sql_log": {"name": "sql_log", "value": test_date, "custom": True, "direct": "", "index": 7}
            }
            input_data_params = {'jobName': task_no, 'jobGroup': 'default',
                                 'taskParam': json.dumps(task_params), 'env': env}
            indexJobAction(input_data=input_data_params, ui_expect={'flag': True})
        # STEP3:断言
        _check_rule_result(ui_expect=ui_expect)
    else:
        raise SeleniumError(f"入参错误，没有 `规则编号`！")


def _check_rule_result(ui_expect=None):
    """
    查看可疑规则预警结果
    :param ruleNo:
    :param ui_expect:
    :param env:
    :return:
    """
    def __count_flow_number(key, number):
        """
        闭包函数，执行sql，统计结果
        :param key:
        :param number:
        :return:
        """
        if number is None:
            logger.debug(f"{key} 的期望值为空，跳过断言！")
            return False
        number = int(number)
        tables = {'预警数量': 'hsamlls.amlls_ext_tradedetail',
                  '交易流水': 'hsamlls.amlls_tradedetail',
                  '账户流水': 'hsamlls.amlls_tradetail_accrequest'}
        sql_1 = f"select count(*) as TOTAL from {tables[key]} WHERE rules_no='{rule_no}' and client_id = '{client_no}'"
        result_list = DB_APP.run_one_sql(sql_1)
        if result_list:
            total = result_list[0].get('TOTAL')
            if total and int(total) >= number:
                logger.info(f'{key}有{total}，符合预期！')
            else:
                error = f'{key}有{total}，不符合预期！'
                logger.error(error)
                raise SeleniumError(error)
        else:
            error = f'{key}查询为空！'
            logger.error(error)
            raise SeleniumError(error)
    rule_no = ui_expect.get('规则', '')
    client_no = ui_expect.get('客户', '')
    warning_number = ui_expect.get('预警数量', 0)
    trade_number = ui_expect.get('交易流水', None)
    trade_account_number = ui_expect.get('账户流水', None)
    __count_flow_number('预警数量', warning_number)
    __count_flow_number('交易流水', trade_number)
    __count_flow_number('账户流水', trade_account_number)